<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>选择排序</title>
  </head>

  <body>
    <h5>选择排序</h5>
    <p>每次找到剩余数组中最小元素，放置数组第一个</p>
    <script>
      function selectionSort(arr) {
        for (let i = 0; i < arr.length - 1; i++) {
          var minIndex = i
          var minVal = arr[minIndex]
          for (let j = i + 1; j < arr.length - 1; j++) {
            if (arr[j] < minVal) {
              minIndex = j
              minVal = arr[minIndex]
            }
          }
          // 交换位置
          arr[minIndex] = arr[i]
          arr[i] = minVal
        }
        return arr
      }

      console.log(selectionSort([5, 1, 4, 2, 3, 8]))
    </script>
  </body>
</html>
